/**
 *
 */
package com.ean.backpack.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ean.backpack.domain.User;
import com.ean.backpack.dto.UserDto;
import com.ean.backpack.repository.UserRepository;
import com.ean.backpack.validator.UserValidator;

/**
 * @author valentin
 *
 */
@Controller
@RequestMapping("/user")
public class UserController extends AbstractController {

	@Autowired
	private UserValidator userValidator;

	@Autowired
	private UserRepository userRepository;

	@InitBinder
	private void userBinder(WebDataBinder binder) {
		binder.setValidator(userValidator);
	}

	/**
	 * Renders the create user form view
	 *
	 * @param model
	 * @return the index view (FTL)
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String showCreateUserForm(Model model) {
		UserDto newUserDto = new UserDto();
		model.addAttribute("newUserDto", newUserDto);
		return "pages/user/create_user";
	}

	/**
	 * Renders the protected view for security test
	 *
	 * @return the protected view
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String createUser(Model model,
			@ModelAttribute("newUserDto") @Valid UserDto newUserDto,
			final RedirectAttributes redirectAttributes, BindingResult result) {
		if (result.hasErrors()) {
			logger.info("error!!");
			return "pages/user/create_user";
		}
		logger.info("new user dto: " + newUserDto);
		User createdUser = userRepository.save(newUserDto.createUser());
		redirectAttributes.addFlashAttribute("createdUserFlag", "true");
		redirectAttributes.addFlashAttribute("createdUser", createdUser);
		return "redirect:/index";
	}

	/**
	 * Checking the existence of an email
	 *
	 * @param email
	 * @return "true" or "false"
	 */
	@RequestMapping(value = "/checkemail", params = "email")
	public @ResponseBody
	String checkMail(@RequestParam String email) {
		logger.debug("checking email : " + email);
		return Boolean.toString(userRepository.findByEmail(email) == null);
	}

}
